import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';

import ContentLayout from '@/component/common/ContentLayout';
import WithdrawWrap from '@/component/balance/WithdrawWrap';
import { Form, Input, Select, DatePicker } from 'antd';
import moment from 'moment';

const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;

import style from '@/page/balance/style.scss';

import StoreListMini from '@/store/StoreListMini';
import adminType from '@/tool/adminType';

class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        onSubmit: PropTypes.func,
        typeFilter: PropTypes.bool,
        downloadExcel: PropTypes.func
    };
    state = {
        date_type: ''
    };
    validateFields = (err, values, callBack) => {
        if (!err) {
            if (this.props.onSubmit) {
                for (let key in values) {
                    if (values[key] === '') delete values[key];
                    //处理date_range
                    if (key == 'date_range') {
                        if (Array.isArray(values[key]) && values[key].length > 0) {
                            values.trade_time = [values[key][0].unix(), values[key][1].unix()].join(',');
                        }
                        delete values[key];
                    }
                }
                if (callBack) callBack(values);
            }
        }
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => this.validateFields(err, values, this.props.onSubmit));
    };
    downloadExcel = () => {
        this.props.form.validateFields((err, values) => this.validateFields(err, values, this.props.downloadExcel));
    };
    handleReset = e => {
        e.preventDefault();
        this.setState({ date_type: '' });
        this.props.form.resetFields();
    };
    rangePickerOnChange = value => {
        if (value.length == 0) this.setState({ date_type: '' });
    };
    dateOptionClick = value => {
        let start, end;
        switch (value) {
        case '今日':
            start = moment().format('YYYY-MM-DD');
            end = moment().add(1, 'days').format('YYYY-MM-DD');
            break;
        case '昨日':
            start = moment().subtract(1, 'days').format('YYYY-MM-DD');
            end = moment().format('YYYY-MM-DD');
            break;
        case '最近7天':
            start = moment().subtract(7, 'days').format('YYYY-MM-DD');
            end = moment().format('YYYY-MM-DD');
            break;
        case '最近30天':
            start = moment().subtract(30, 'days').format('YYYY-MM-DD');
            end = moment().format('YYYY-MM-DD');
            break;
        }
        if (start !== '' && end !== '') {
            this.props.form.setFieldsValue({ date_range: [ moment(start), moment(end) ] });
        }
        this.setState({ date_type: value });
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const storeListMini = StoreListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });

        const { date_type } = this.state;
        const dateTypeBtns = ['今日', '昨日', '最近7天', '最近30天'].map((val, index) => {
            return <a key={index} className={val == date_type ? style['select'] : null} href="javascript:void(0);"
                onClick={() => this.dateOptionClick(val)}>{val}</a>
        });
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                {adminType() == 1 &&
                <FormItem label="门店">
                    {getFieldDecorator('store_id', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择门店" style={{ width: 150 }}>
                            <Option key="default" value="">不限</Option>
                            {storeOptionList}
                        </Select>
                    )}
                </FormItem>}
                <FormItem label="时间">
                    {getFieldDecorator('date_range', {
                        initialValue: ''
                    })(
                        <RangePicker onChange={this.rangePickerOnChange}/>
                    )}
                </FormItem>
                <FormItem>
                    <div className={style['date-option']}>
                        {dateTypeBtns}
                    </div>
                </FormItem>
                <FormItem>
                    <a className={style['info-half-btn']} href="javascript:void(0);">更多筛选</a>
                </FormItem>
                <FormItem>
                    <a style={{ marginLeft: 40 }} className={style['primary-half-btn']} onClick={this.downloadExcel}>下载excel表格</a>
                </FormItem>
                <div style={{ height: 15 }} />
                {this.props.typeFilter &&
                <FormItem label="财务类型">
                    {getFieldDecorator('trade_type', {
                        initialValue: '0'
                    })(
                        <Select placeholder="选择财务类型" style={{ width: 150 }}>
                            <Option value="0">全部类型</Option>
                            <Option value="1">房租</Option>
                            <Option value="2">收佣</Option>
                            <Option value="3">付佣</Option>
                            <Option value="4">维修</Option>
                            <Option value="5">分期首付房租</Option>
                            <Option value="6">分期房租</Option>
                            <Option value="7">房租分期手续费</Option>
                            <Option value="8">房租分期冻结</Option>
                            <Option value="9">房租分期押金冻结</Option>
                            <Option value="10">分期押金解冻</Option>
                            <Option value="11">分期房租解冻</Option>
                            <Option value="12">押金退还给租客</Option>
                            <Option value="13">退还剩余本金</Option>
                        </Select>
                    )}
                </FormItem>}
                <FormItem label="精确查询">
                    {getFieldDecorator('trade_no', {
                        initialValue: ''
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={style['submit-btn']} type="submit">搜索</button>
                </FormItem>
                <FormItem>
                    <button className={style['info-btn']} type="reset" onClick={this.handleReset}>重置</button>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

class Layout extends Component {
    static propTypes = {
        children: PropTypes.node,
        loading: PropTypes.bool,
        onSubmit: PropTypes.func,
        downloadExcel: PropTypes.func,
        typeFilter: PropTypes.bool,
        sum: PropTypes.object
    };
    static defaultProps = {
        typeFilter: true
    };
    render() {
        const { sum } = this.props;
        return (
            <ContentLayout navTitle="财务"  loading={this.props.loading}>
                <div className={style['top-wrap']}>
                    {adminType() == 1 && <WithdrawWrap />}
                    <div className={style['top-filter']}>
                        <FilterWrapped onSubmit={this.props.onSubmit} typeFilter={this.props.typeFilter} downloadExcel={this.props.downloadExcel} />
                    </div>
                    <div className={style['balance-type-nav']}>
                        <NavLink exact to="/财务" activeClassName={style['active']}>全部</NavLink>
                        <NavLink exact to="/财务/收入" activeClassName={style['active']}>收入</NavLink>
                        <NavLink exact to="/财务/支出" activeClassName={style['active']}>支出</NavLink>
                        <NavLink exact to="/财务/冻结" activeClassName={style['active']}>冻结</NavLink>
                        <NavLink exact to="/财务/收款" activeClassName={style['active']}>收款</NavLink>
                        {sum &&
                        <div className={style['balance-sum']}>
                            <span className={style['sum-in']}>收入：<em>{sum.in / 100}元/{sum.in_count}笔</em></span> <span className={style['sum-out']}>支出：<em>-{sum.out / 100}元/{sum.out_count}笔</em></span>
                        </div>}
                    </div>
                    {this.props.children}
                </div>
            </ContentLayout>
        );
    }
}

export default Layout;